package com.zhanghu.backendZray.listener;

import cn.hutool.core.util.IdUtil;
import org.slf4j.MDC;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.zhanghu.backendZray.constants.CommonConstant.REQUEST_ID;

/**
 * 请求监听器
 */
@WebListener
public class MyServletRequestListener implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        MDC.put(REQUEST_ID, IdUtil.fastSimpleUUID());
//        System.err.println("request enter....");
        // 请求到达时执行
        // 获取 ServletRequest 对象
        ServletRequest request = sre.getServletRequest();

        // 检查是否是 HTTP 请求
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            // 获取请求的基本信息
            String requestURI = httpRequest.getRequestURI();   // 请求的 URI
            String clientIP = httpRequest.getRemoteAddr();     // 客户端 IP 地址
            String userAgent = httpRequest.getHeader("User-Agent"); // 获取请求头中的 User-Agent

            // 获取请求参数（例如 GET 或 POST 请求中的参数）
            Map<String, String[]> parameterMap = httpRequest.getParameterMap();
            String paramValue = httpRequest.getParameter("someParam"); // 获取参数 'someParam' 的值

            // 打印或处理请求数据
//            System.err.println("Request URI: " + requestURI);
//            System.err.println("Client IP: " + clientIP);
//            System.err.println("User-Agent: " + userAgent);
//            System.err.println("someParam: " + JSON.toJSONString(parameterMap));
        }
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        // 请求销毁时执行
//        System.err.println("Request destroyed: " + sre.getServletRequest());
        MDC.clear();
    }
}